import React, { useEffect, useMemo } from 'react';
import { CheckOutlined, CloseOutlined, PlusOutlined } from '@ant-design/icons';
import { Button, Cascader, Col, Drawer, Form, Input, InputNumber, Row, Select, Space, Upload, message } from 'antd';
import { CloseEnum, DialogEnum } from '..';
import { useForm } from 'antd/es/form/Form';
import { educationDict, genderDict, receiveDict } from '@/utils/dicts';
import { city } from '@/utils/city';
import { career } from '@/utils/career';
import { type RowType, type RegistryType } from '@/api/user';

type CurdDialogProps = {
  isDrawerOpen: boolean
  isDialogState: DialogEnum
  formInfo: RowType
  onClose: (closeType: CloseEnum, formInfo?: RegistryType) => void
}

const DialogForm: React.FC<CurdDialogProps> = ({ isDrawerOpen, isDialogState, formInfo, onClose }) => {
  const baseUrl = import.meta.env.VITE_APP_BASE_URL

  const isEdit = useMemo(() => isDialogState === DialogEnum['编辑'], [isDialogState])
  
  const [form] = useForm()

  const onCloseDrawer = () => {
    onClose(CloseEnum['取消'])
    form.resetFields()
  }

  const onConfirm = async () => {
    try {
      const values = await form.validateFields()
      console.log(values, 999)
      // console.log(form.getFieldsValue(), values)
      onClose(CloseEnum['确认'], values)
    } catch (e) {
      console.log(e)
    }
  }

  const normFile = (e: { file: { status: string; response: { code: number; msg: any; }; }; fileList: { response: { data: { name: any; url: any; }; }; }[]; }) => {
    try {
      if (Array.isArray(e)) {
        return e;
      }
  
      if (e?.file.status === 'done') {
        if (e?.file.response.code !== 200) {
          message.error(e?.file.response.msg || '')
          throw Error()
        }
        return e?.fileList.map((item: { response: { data: { name: string, url: string; }; }; }) => {
          if (item.response) {
            return {
              name: item.response.data.name,
              url: item.response.data.url
            }
          }
          return item
        })
      }
      return e?.fileList
    } catch (e) {
      console.log(e)
    }
  }

  useEffect(() => {
    if (isDrawerOpen && isEdit) {
      form.setFieldsValue(formInfo)
    }
  }, [isDrawerOpen, isDialogState])

  return (
    <>
      <Drawer
        destroyOnClose={true}
        title={isEdit ? '修改账户信息' : '创建账户'}
        width={720}
        closable={false}
        onClose={onCloseDrawer}
        open={isDrawerOpen}
        styles={{
          body: {
            paddingBottom: 80,
          },
        }}
        extra={
          <Space>
            <CloseOutlined className='cursor-pointer' onClick={onCloseDrawer} />
          </Space>
        }

        footer={
          <Space className='flex justify-end'>
            <Button icon={<CloseOutlined />} onClick={onCloseDrawer}>关 闭</Button>
            <Button type='primary' icon={<CheckOutlined />} onClick={onConfirm}>确 认</Button>
          </Space>
        }
      >
        <Form form={form} layout="vertical" requiredMark={true}>
          <Row gutter={20}>
            <Col span={12}>
              <Form.Item
                name="username"
                label="用户名"
                rules={[{ required: true, message: '请输入用户名' }]}
              >
                <Input disabled={isEdit} placeholder="请输入用户名" />
              </Form.Item>
            </Col>
            {
              !isEdit && <>
                <Col span={12}>
                  <Form.Item
                    name="password"
                    label="密码"
                    rules={[{ required: !isEdit, message: '请输入密码' }]}
                  >
                    <Input.Password type="" placeholder='请输入密码' />
                  </Form.Item>
                </Col>

                <Col span={12}>
                  <Form.Item
                    name="pwdRepeat"
                    label="确认密码"
                    rules={[{ required: !isEdit, message: '请输入确认密码' }]}
                  >
                    <Input.Password placeholder='请输入确认密码' />
                  </Form.Item>
                </Col>
              </>
            
            }

            <Col span={12}>
              <Form.Item
                name="phoneNumber"
                label="手机号码"
                rules={[{ required: true, message: '请输入手机号码' }]}
              >
                <Input placeholder='请输入手机号码' />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="gender" label="性别" rules={[{ required: true, message: '请选择性别' }]}>
                <Select placeholder="请选择性别" allowClear>
                  {
                    genderDict.map(item => {
                      return (
                        <Select.Option value={item.code} key={item.code}>
                          <div>
                            <span className='float-left'>{item.value}</span>
                            <span className='float-right'>{item.code}</span>
                          </div>
                        </Select.Option>
                      )
                    })
                  }
                </Select>
              </Form.Item>
            </Col>

            <Col span={12}>
              <Form.Item label="年龄" name="age" rules={[{ required: true, message: '请输入年龄' }]}>
                <InputNumber min={0} addonAfter="岁" placeholder="请输入年龄" className='w-full' />
              </Form.Item>
            </Col>

            <Col span={12}>
              <Form.Item name="education" label="学历" rules={[{ required: true, message: '请选择学历' }]}>
                <Select placeholder="请选择学历" allowClear>
                  {
                    educationDict.sort((a, b) => b.order - a.order).map(item => {
                      return (
                        <Select.Option value={item.code} key={item.code}>
                          <div>
                            <span className='float-left'>{item.value}</span>
                            <span className='float-right'>{item.code}</span>
                          </div>
                        </Select.Option>
                      )
                    })
                  }
                </Select>
              </Form.Item>
            </Col>

            <Col span={12}>
              <Form.Item label="收入范围" name="receive" rules={[{ required: true, message: '请选择收入范围' }]}>
                <Select placeholder="请选择收入范围" allowClear>
                  {
                    receiveDict.sort((a, b) => b.order - a.order).map(item => {
                      return (
                        <Select.Option value={item.code} key={item.code}>
                          <div>
                            <span className='float-left'>{item.value}</span>
                            <span className='float-right'>{item.code}</span>
                          </div>
                        </Select.Option>
                      )
                    })
                  }
                </Select>
              </Form.Item>
            </Col>

            <Col span={12}>
              <Form.Item label="所在地区" name="city" rules={[{ required: true, message: '请选择所在地区' }]}>
                <Cascader options={city} placeholder="请选择地区" fieldNames={{ label: 'name', value: 'code' }} allowClear />
              </Form.Item>
            </Col>

            <Col span={12}>
              <Form.Item
                name="email"
                label="邮箱"
                rules={[{ required: false, message: '请输入邮箱', type: 'email' }]}
              >
                <Input placeholder='请输入邮箱' />
              </Form.Item>
            </Col>

            <Col span={12}>
              <Form.Item label="职业" name="career">
                <Cascader options={career} placeholder="请选择地区" fieldNames={{ label: 'name', value: 'code' }} allowClear />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="兴趣爱好" name="hobby">
                <Input placeholder="请输入兴趣爱好" />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={20}>
            <Col span={24}>
              <Form.Item label="备注" name="remark">
                <Input.TextArea placeholder="请输入备注" />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item label="上传头像" valuePropName="fileList" getValueFromEvent={normFile} name="avatarObj">
            <Upload 
              action={`${baseUrl}/upload/file`}
              listType="picture-card"
              maxCount={1}
              name='file'
              headers={{authorization: `Bearer ${localStorage.getItem('token')}`}}
            >
              <button style={{ border: 0, background: 'none' }} type="button">
                <PlusOutlined />
                <div style={{ marginTop: 8 }}>Upload</div>
              </button>
            </Upload>
          </Form.Item>

          <Form.Item label="上传照片集" valuePropName="fileList" getValueFromEvent={normFile} name="fileList">
            <Upload
              action={`${baseUrl}/upload/file`}
              listType="picture-card"
              name='file'
              headers={{ authorization: `Bearer ${localStorage.getItem('token')}`}}
            >
              <button style={{ border: 0, background: 'none' }} type="button">
                <PlusOutlined />
                <div style={{ marginTop: 8 }}>Upload</div>
              </button>
            </Upload>
          </Form.Item>
        </Form>
      </Drawer>
    </>
  );
};

export default DialogForm;